#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>

extern "C" {
    #include <oauth.h>
}

void oauth_post()
{
    const char *url      = "http://twitter.com/statuses/public_timeline.xml";
    const char *c_key    = NULL;
    const char *c_secret = NULL;
    char *t_key    = NULL;
    char *t_secret = NULL;

    char *post_args = NULL;
    char *req_url   = NULL;
    char *reply     = NULL;
    
    req_url = oauth_sign_url2(url,&post_args, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret);

    std::cout << "REQUEST URL:  " << req_url << "\n";

    char **rv = NULL;
    reply = oauth_http_post(req_url,post_args);

    std::cout << "HTTP REPLY: " << reply << "\n";

    int rc = oauth_split_url_parameters(reply, &rv);
    qsort(rv, rc, sizeof(char*), oauth_cmpstringp);

    if( rc==2 
            && !strncmp(rv[0],"oauth_token=",11)
            && !strncmp(rv[1],"oauth_token_secret=",18) ){
        t_key=strdup(&(rv[0][12]));
        t_secret=strdup(&(rv[1][19]));
        std::cout << "key: << '" << t_key << "'\n";
        std::cout << "secret: '"<< t_secret <<"'\n";
    }   

    if(req_url) free(req_url);
    if(post_args) free(post_args);
    if(reply) free(reply);
    if(t_secret) free(t_secret);
    if(t_key) free(t_key);
}

void oauth_get()
{
    const char *url      = "http://twitter.com/statuses/user_timeline.xml";
    const char *c_key    = "key";
    const char *c_secret = "secret";
    char *t_key    = NULL;
    char *t_secret = NULL;

    char *req_url   = NULL;
    char *reply     = NULL;
    
    req_url = oauth_sign_url2(url,NULL, OA_HMAC, NULL, c_key, c_secret, NULL, NULL);

    std::cout << "REQUEST URL:  " << req_url << "\n";

    reply = oauth_http_get(req_url,NULL);

    if(!reply)
        std::cout << "Token-failed" << std::endl;
    else{
        std::cout << "HTTP REPLY: " << reply << "\n";

        char **rv = NULL;
        int rc = oauth_split_url_parameters(reply, &rv);
        qsort(rv, rc, sizeof(char*), oauth_cmpstringp);

        if( rc==2 
                && !strncmp(rv[0],"oauth_token=",11)
                && !strncmp(rv[1],"oauth_token_secret=",18) ){
            t_key=strdup(&(rv[0][12]));
            t_secret=strdup(&(rv[1][19]));
            std::cout << "key: << '" << t_key << "'\n";
            std::cout << "secret: '"<< t_secret <<"'\n";
        }   

        if(rv) free(rv);
    }

    if(req_url) free(req_url);
    if(reply) free(reply);
    if(t_secret) free(t_secret);
    if(t_key) free(t_key);
}

int main() {
  
    oauth_get();
    return 0;
}
